package com.hx.mypetstore.ui.Login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.support.hwid.HuaweiIdAuthManager;
import com.huawei.hms.support.hwid.request.HuaweiIdAuthParams;
import com.huawei.hms.support.hwid.request.HuaweiIdAuthParamsHelper;
import com.huawei.hms.support.hwid.result.AuthHuaweiId;
import com.huawei.hms.support.hwid.service.HuaweiIdAuthService;
import com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton;
import com.hx.mypetstore.Bean.UserBean;
import com.hx.mypetstore.MainActivity;
import com.hx.mypetstore.R;
import com.hx.mypetstore.constant.SPConstants;
import com.hx.mypetstore.network.HttpURL;
import com.hx.mypetstore.util.SPUtil;
import com.hx.mypetstore.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class LoginActivity extends AppCompatActivity  implements View.OnClickListener{

    public static final int REQUEST_SIGN_IN_LOGIN = 1002;
    private static final String TAG = "LoginAct";

    // 账号
    private AppCompatEditText mEtUserName;
    // 密码
    private AppCompatEditText mEtPassword;

    // 华为账号登录按钮
    private HuaweiIdAuthButton mHuaweiIdAuthButton;

    // 华为账号登录客户端
    private HuaweiIdAuthService mAuthService;

    // 本地用户数据
    private List<UserBean> mLocalData;

    // 返回
    private ImageView mIvBack;

//    // 登录加载框
//    private LoadingDialog loadingDialog;

    // FIDO2相关处理
//    private Fido2Handler fido2Handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // 设置屏幕不能截屏和录屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        
        // 初始化View
        initView();

        // 提示进入的Kit
        ToastUtil.getInstance().showShort(this, R.string.toast_account);

    }

    private void initView() {
        // 顶部返回
        ImageView mIvBack = findViewById(R.id.title_back);

        mEtUserName = findViewById(R.id.login_username);
        mEtPassword = findViewById(R.id.login_password);


        mIvBack.setOnClickListener(this);

        findViewById(R.id.login_login).setOnClickListener(this);
        findViewById(R.id.login_register).setOnClickListener(this);

        mHuaweiIdAuthButton = findViewById(R.id.hwid_signin);
        // 注册监听器
        mHuaweiIdAuthButton.setOnClickListener(this);
        // 设置主题
        mHuaweiIdAuthButton.setTheme(HuaweiIdAuthButton.THEME_NO_TITLE);
        // 设置圆角半径
        mHuaweiIdAuthButton.setCornerRadius(HuaweiIdAuthButton.CORNER_RADIUS_LARGE);
        // 设置配色方案
        mHuaweiIdAuthButton.setColorPolicy(HuaweiIdAuthButton.COLOR_POLICY_WHITE);

    }

    /**
     * 初始化当前用户信息
     */
    private void onInitLocalUser() {
        String localStr = (String) SPUtil.get(this, SPConstants.KEY_LOCAL_USER, "");
        if (TextUtils.isEmpty(localStr)) {
            mLocalData = null;
            return;
        }
        try {
            Gson gson = new Gson();
            mLocalData = gson.fromJson(localStr, new TypeToken<List<UserBean>>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "onInitLocalUser json format error");
        }
    }
    /**
     * 登录
     */
    private void onLogin() {
        String url = HttpURL.LOGIN;
        if (mEtUserName.getText() != null && mEtPassword.getText() != null) {
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody requestBody = new FormBody.Builder()
                    .add("phone", String.valueOf(mEtUserName.getText()))
                    .add("password",String.valueOf(mEtPassword.getText()))
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d(TAG, "onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        Log.d(TAG, String.valueOf(jsonObject.getBoolean("success")));
                        if (!jsonObject.getBoolean("success")) {
                            Looper.prepare();
                            Toast toast = Toast.makeText(getApplication(), jsonObject.getString("message"), Toast.LENGTH_LONG);
                            toast.show();
                            Looper.loop();
                        }else {
                            Gson gson = new Gson();
                            UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                            SPUtil.put(getApplication(), SPConstants.KEY_LOGIN, true);
                            SPUtil.put(getApplication(), SPConstants.KEY_HW_LOGIN, false);
                            SPUtil.put(getApplication(), SPConstants.KEY_NICK_NAME, user.getUsername());
                            SPUtil.put(getApplication(),SPConstants.KEY_LOCAL_USER,user.getPhone());
                            startActivity(new Intent(getApplication(), MainActivity.class));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }else{
            Looper.prepare();
            Toast.makeText(this,"账号密码不得为空！！！",Toast.LENGTH_LONG).show();
            Looper.loop();
        }
    }
    /**
     * 保存用户信息到SharedPreferences
     */
    private void onHuaweiIdLoginSuccess(AuthHuaweiId huaweiAccount) {
        // 保存华为账号 openId
        String openId = huaweiAccount.getOpenId();
        SPUtil.put(this, SPConstants.KEY_HW_OEPNID, openId);
        try {
            JSONObject jsonObject = new JSONObject();
            // 保存华为帐号头像
            jsonObject.put(SPConstants.KEY_HEAD_PHOTO, huaweiAccount.getAvatarUriString());
            SPUtil.put(this, openId, jsonObject.toString());
        } catch (JSONException ignored) {
            Log.e(TAG, "onHuaweiIdLoginSuccess json format error");
        }
        // 是否登录
        SPUtil.put(this, SPConstants.KEY_LOGIN, true);
        // 华为登录
        SPUtil.put(this, SPConstants.KEY_HW_LOGIN, true);
        // 保存华为帐号昵称
        SPUtil.put(this, SPConstants.KEY_NICK_NAME, huaweiAccount.getDisplayName());


        //
        String url = HttpURL.IFVERIFY;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("openID", huaweiAccount.getOpenId())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Log.e(TAG, jsonObject.toString() );
                    Log.e(TAG, "是否绑定 "+jsonObject.getBoolean("data") );
                    if (!jsonObject.getBoolean("data")) {
                            startActivity(new Intent(getApplication(), VerifyActivity.class));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        startActivity(new Intent(this,MainActivity.class));
    }
    /**
     * 华为账号登录
     */
    private void onHuaweiIdLogin() {
        // 构造华为账号登录选项
        HuaweiIdAuthParams authParam = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                .createParams();

        mAuthService = HuaweiIdAuthManager.getService(LoginActivity.this, authParam);

        // 获取登录授权页面的Intent，并通过startActivityForResult拉起授权页面
        startActivityForResult(mAuthService.getSignInIntent(), REQUEST_SIGN_IN_LOGIN);
    }
    /**
     * 静默登录
     */
    private void silentSignIn() {
        // 配置授权参数
        HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                .createParams();
        // 初始化HuaweiIdAuthService对象
        mAuthService = HuaweiIdAuthManager.getService(LoginActivity.this, authParams);
        // 发起静默登录请求
        Task<AuthHuaweiId> task = mAuthService.silentSignIn();
        // 处理授权成功的登录结果
        task.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
            @Override
            public void onSuccess(AuthHuaweiId authHuaweiId) {
                // 已经授权
                onHuaweiIdLoginSuccess(authHuaweiId);
                Log.d(TAG, authHuaweiId.getDisplayName() + " silent signIn success ");
            }
        });
        // 处理授权失败的登录结果
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                if (e instanceof ApiException) {
                    ApiException apiException = (ApiException) e;
                    if (apiException.getStatusCode() == 2002) {
                        // 未授权，调用onHuaweiIdLogin方法拉起授权界面，让用户授权
                        onHuaweiIdLogin();
                        Intent signInIntent = mAuthService.getSignInIntent();
                        Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(signInIntent);
                        // 华为帐号登录成功
                        AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
                        Log.i(TAG, "signIn success");
                        Log.i(TAG, "DisplayName: " + huaweiAccount.getDisplayName());
                        Log.i(TAG, "AvatarUriString: " + huaweiAccount.getAvatarUriString());
                        //登录成功处理
                        onHuaweiIdLoginSuccess(huaweiAccount);
                    }
                }
            }
        });
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                // 返回
                startActivity(new Intent(this, MainActivity.class));
                break;
            case R.id.login_login:
                // 登录
                onLogin();
                break;
            case R.id.login_register:
                // 注册
                onRegister();
                break;
            case R.id.hwid_signin:
                // 华为账号登录
                silentSignIn();
                break;
            default:
                break;
        }
    }

    private void onRegister() {
        startActivity(new Intent(this,RegisterActivity.class));
    }

}